package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.domain.Contacts;
import com.example.demo.domain.User;
import com.example.demo.service.ContactsService;
import com.example.demo.service.UserService;
import com.example.demo.utils.Result;
import com.example.demo.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/contacts")
@RequiredArgsConstructor
@CrossOrigin
public class ContactsController {

    private final ContactsService contactsService;
    private final UserService userService;

    /**
     * 查询当前用户的联系人列表
     * @param request HTTP请求
     * @return 联系人列表
     */
    @GetMapping("/queryContactByUserId")
    public Result<List<Contacts>> queryContactByUserId(HttpServletRequest request) {
        return contactsService.queryContactByUserId(request);
    }
    
    /**
     * 添加联系人
     * @param request HTTP请求
     * @param contactUserId 要添加的联系人用户ID
     * @param remarkName 备注名称（可选）
     * @param groupName 分组名称（可选）
     * @return 添加结果
     */
    @PostMapping("/addContact")
    public Result<String> addContact(
            HttpServletRequest request,
            @RequestParam Long contactUserId,
            @RequestParam(required = false) String remarkName,
            @RequestParam(required = false) String groupName) {
        
        // 验证token
        String token = request.getHeader("authorization");
        if (!StringUtils.hasText(token)) {
            return Result.error("未登录");
        }
        
        // 获取当前用户
        Map<String, String> tokenMap = TokenUtil.parseToken(token);
        User currentUser = userService.getOne(
            new LambdaQueryWrapper<User>().eq(User::getUserName, tokenMap.get("userName"))
        );
        
        if (currentUser == null) {
            return Result.error("用户不存在");
        }
        
        // 验证联系人是否存在
        User contactUser = userService.getById(contactUserId);
        if (contactUser == null) {
            return Result.error("要添加的联系人不存在");
        }
        
        // 验证是否已经添加过该联系人
        LambdaQueryWrapper<Contacts> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(Contacts::getUserId, currentUser.getId())
                   .eq(Contacts::getContactId, contactUserId);
        
        long count = contactsService.count(checkWrapper);
        if (count > 0) {
            return Result.error("该联系人已存在");
        }
        
        // 创建联系人对象
        Contacts contact = new Contacts();
        contact.setUserId(currentUser.getId().longValue());
        contact.setContactId(contactUserId);
        contact.setRemarkName(remarkName);
        contact.setGroupName(groupName);
        contact.setRelationStatus(1); // 1表示正常关系
        contact.setIsBlacklisted(false);
        
        Date now = new Date();
        contact.setCreateTime(now);
        contact.setUpdateTime(now);
        
        // 保存联系人
        contactsService.addContact(contact);
        
        return Result.success("添加联系人成功");
    }
    
    /**
     * 删除联系人
     * @param request HTTP请求
     * @param contactId 联系人记录ID
     * @return 删除结果
     */
    @DeleteMapping("/deleteContact")
    public Result<String> deleteContact(
            HttpServletRequest request,
            @RequestParam Long contactId) {
        
        // 验证token
        String token = request.getHeader("authorization");
        if (!StringUtils.hasText(token)) {
            return Result.error("未登录");
        }
        // 123123
        // 获取当前用户
        Map<String, String> tokenMap = TokenUtil.parseToken(token);
        User currentUser = userService.getOne(
            new LambdaQueryWrapper<User>().eq(User::getUserName, tokenMap.get("userName"))
        );
        
        if (currentUser == null) {
            return Result.error("用户不存在");
        }
        
        // 验证联系人记录是否存在且属于当前用户
        LambdaQueryWrapper<Contacts> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Contacts::getId, contactId)
              .eq(Contacts::getUserId, currentUser.getId());
        
        Contacts contact = contactsService.getOne(wrapper);
        if (contact == null) {
            return Result.error("联系人记录不存在或不属于当前用户");
        }
        
        // 删除联系人
        contactsService.removeById(contactId);
        
        return Result.success("删除联系人成功");
    }
}
